package ThreadDemo;

import java.util.PriorityQueue;
import java.util.TimerTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-27
 * Time: 19:03
 */
//模拟实现一个定时器
class RunnableTask implements Comparable<RunnableTask>{//描述任务
    private Runnable task;
    private long moment;

    public RunnableTask(Runnable task,long moment){
        this.task = task;
        this.moment = moment;
    }

    //获取时间
    public long getMoment(){
        return moment;
    }

    public void run(){
        task.run();
    }


    //优先级队列的比较方式
    @Override
    public int compareTo(RunnableTask o) {
        return (int)(this.moment - o.moment);
    }
}
public class MyTimer{
    //使用优先级队列存储任务
    private PriorityQueue<RunnableTask> queue = new PriorityQueue<>();

    public MyTimer(){
        //创建一个线程用来执行任务
        Thread t = new Thread(() -> {
            //因为不知道任务什么时候执行，所以不停的取任务
            try{
                while(true){
                    synchronized(Object.class){
                        while(queue.isEmpty()){
                            Object.class.wait();//等待队列添加元素
                        }

                        //取出任务，判断是否执行
                        RunnableTask task = queue.peek();
                        if(System.currentTimeMillis() < task.getMoment()){
                            Object.class.wait(task.getMoment() - System.currentTimeMillis());
                        }else{
                            //执行任务
                            task.run();
                            queue.poll();
                        }
                    }
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });
        t.start();//启动线程
    }

    //往队列中添加任务
    public void schedule(Runnable task,long moment){
        synchronized (Object.class){
            //创建RunnableTask对象
            RunnableTask runnableTask = new RunnableTask(task, System.currentTimeMillis() + moment);
            queue.offer(runnableTask);
            Object.class.notify();
        }
    }

    public static void main(String[] args) {
        //创建定时器
        MyTimer myTimer = new MyTimer();

        //添加任务
        myTimer.schedule(()->{
            System.out.println("hello 1000");
        },1000);

        myTimer.schedule(()->{
            System.out.println("hello 2000");
        },2000);

        myTimer.schedule(()->{
            System.out.println("hello 3000");
        },3000);

        System.out.println("hello main");
    }
}